<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { currentKnowledge, formLoading, operationType } from '@/views/kg/knowledge/utils/hooks';
import { useKnowledgeStore } from '@/store/kg/knowledge';

// 表单规则
const rules = reactive({
  name: [{ required: true, message: '请输入知识点名称', trigger: 'blur' }],
  level: [{ required: true, message: '请选择难度级别', trigger: 'change' }],
  courseId: [{ required: true, message: '请选择所属课程', trigger: 'change' }],
});

// 难度级别选项
const levelOptions = [
  { label: '基础', value: 1 },
  { label: '简单', value: 2 },
  { label: '一般', value: 3 },
  { label: '困难', value: 4 },
  { label: '进阶', value: 5 },
];

// 自定义标签输入
const tagInputVisible = ref(false);
const tagInputValue = ref('');
const tagInputRef = ref();

// 知识点store
const knowledgeStore = useKnowledgeStore();
const formRef = ref();

// 确保知识点的标签字段是数组
const ensureTagsArray = () => {
  if (!currentKnowledge.value.tags) {
    currentKnowledge.value.tags = [];
  } else if (!Array.isArray(currentKnowledge.value.tags)) {
    currentKnowledge.value.tags = [currentKnowledge.value.tags];
  }
};

// 加载课程列表
onMounted(async () => {
  await knowledgeStore.getCourseList();
  ensureTagsArray();
});

// 处理关闭标签
const handleClose = (tag: string) => {
  ensureTagsArray();
  currentKnowledge.value.tags = currentKnowledge.value.tags.filter((t: string) => t !== tag);
};

// 显示标签输入框
const showTagInput = () => {
  tagInputVisible.value = true;
  // 在下一个DOM更新周期后聚焦输入框
  setTimeout(() => {
    tagInputRef.value?.input?.focus();
  });
};

// 处理标签输入确认
const handleTagInputConfirm = () => {
  if (tagInputValue.value) {
    ensureTagsArray();
    // 如果标签不存在，才添加
    if (!currentKnowledge.value.tags.includes(tagInputValue.value)) {
      currentKnowledge.value.tags.push(tagInputValue.value);
    }
  }
  tagInputVisible.value = false;
  tagInputValue.value = '';
};

// 添加预设标签
const addTag = (tag: string) => {
  ensureTagsArray();
  if (!currentKnowledge.value.tags.includes(tag)) {
    currentKnowledge.value.tags.push(tag);
  }
};

// 保存知识点方法
const onSaveKnowledge = async (formRef: any) => {
  if (!formRef) return false;

  try {
    const valid = await formRef.validate().catch(() => false);
    if (!valid) {
      ElMessage.error('表单验证失败，请检查表单项');
      return false;
    }

    formLoading.value = true;
    try {
      if (operationType.value === 'add') {
        if (!currentKnowledge.value.courseId && knowledgeStore.selectedCourseId) {
          currentKnowledge.value.courseId = knowledgeStore.selectedCourseId;
        }
        await knowledgeStore.createKnowledge(
          String(currentKnowledge.value.courseId),
          currentKnowledge.value
        );
      } else {
        await knowledgeStore.updateKnowledge(String(currentKnowledge.value.nodeId), currentKnowledge.value);
      }
      return true;
    } finally {
      formLoading.value = false;
    }
  } catch (error) {
    console.error('保存知识点失败:', error);
    return false;
  }
};

// 暴露方法给父组件
defineExpose({
  onSaveKnowledge,
  formRef,
});
</script>

<template>
  <el-form ref="formRef" :model="currentKnowledge" :rules="rules" label-width="100px">
    <el-form-item label="知识点名称" prop="name">
      <el-input v-model="currentKnowledge.name" placeholder="请输入知识点名称" />
    </el-form-item>

    <el-form-item label="所属课程" prop="courseId">
      <el-select
        v-model="currentKnowledge.courseId"
        placeholder="请选择所属课程"
        style="width: 100%;"
        filterable
      >
        <el-option
          v-for="course in knowledgeStore.courseList"
          :key="course.nodeId"
          :label="course.name"
          :value="course.nodeId"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="难度级别" prop="level">
      <el-radio-group v-model="currentKnowledge.level">
        <el-radio :label="1">
          <el-tag type="info">基础</el-tag>
        </el-radio>
        <el-radio :label="2">
          <el-tag type="success">简单</el-tag>
        </el-radio>
        <el-radio :label="3">
          <el-tag type="warning">一般</el-tag>
        </el-radio>
        <el-radio :label="4">
          <el-tag type="danger">困难</el-tag>
        </el-radio>
        <el-radio :label="5">
          <el-tag type="primary">进阶</el-tag>
        </el-radio>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="知识点概述" prop="summary">
      <el-input
        v-model="currentKnowledge.summary"
        type="textarea"
        :rows="4"
        placeholder="请输入知识点概述"
      />
    </el-form-item>

    <el-form-item label="标签">
      <div class="tag-container">
        <el-tag
          v-for="tag in currentKnowledge.tags"
          :key="tag"
          class="tag-item"
          closable
          :disable-transitions="false"
          @close="handleClose(tag)"
        >
          {{ tag }}
        </el-tag>

        <el-input
          v-if="tagInputVisible"
          ref="tagInputRef"
          v-model="tagInputValue"
          class="tag-input"
          size="small"
          @keyup.enter="handleTagInputConfirm"
          @blur="handleTagInputConfirm"
        />

        <el-button v-else class="button-new-tag" size="small" @click="showTagInput">
          + 新标签
        </el-button>
      </div>

      <!-- 常用标签建议 -->
      <div class="common-tags mt-2">
        <span class="text-gray-500 text-sm mr-2">常用标签：</span>
        <el-tag
          v-for="tag in knowledgeStore.commonTags"
          :key="tag"
          class="common-tag-item"
          size="small"
          :disable-transitions="true"
          effect="plain"
          @click="addTag(tag)"
        >
          {{ tag }}
        </el-tag>
      </div>
    </el-form-item>
  </el-form>
</template>

<style scoped>
.tag-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.tag-item {
  margin-right: 8px;
  margin-bottom: 8px;
}

.tag-input {
  width: 90px;
  margin-right: 8px;
  margin-bottom: 8px;
  vertical-align: bottom;
}

.button-new-tag {
  margin-bottom: 8px;
}

.common-tags {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.common-tag-item {
  cursor: pointer;
  margin-right: 8px;
  margin-bottom: 4px;
}

.common-tag-item:hover {
  opacity: 0.8;
}

.mt-2 {
  margin-top: 8px;
}

.text-gray-500 {
  color: #909399;
}

.text-sm {
  font-size: 0.875rem;
}

.mr-2 {
  margin-right: 0.5rem;
}
</style>
